import React, { useState, useMemo } from 'react';
import {
  Card,
  Row,
  Col,
  Button,
  Space,
  Typography,
  Tag,
  Tooltip,
  Table,
  Switch,
  Badge,
  message
} from 'antd';
import {
  CheckOutlined,
  CopyOutlined,
  DownloadOutlined,
  EyeOutlined,
  ThunderboltOutlined,
  DiffOutlined,
  BulbOutlined,
  SettingOutlined,
  CodeOutlined,
  SwapOutlined
} from '@ant-design/icons';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneLight, oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { OptimizationSuggestion } from '../../types/analysis';
import './OptimizationView.css';

const { Title, Text, Paragraph } = Typography;

interface OptimizationViewProps {
  originalSql: string;
  optimizedSql: string;
  explanation?: string;
  optimizations?: OptimizationSuggestion[];
  onApplyOptimization?: (sql: string) => void;
  onApplyPartialOptimization?: (optimizations: OptimizationSuggestion[]) => void;
  showDiff?: boolean;
  theme?: 'light' | 'dark';
}

const OptimizationView: React.FC<OptimizationViewProps> = ({
  originalSql,
  optimizedSql,
  explanation,
  optimizations = [],
  onApplyOptimization,
  onApplyPartialOptimization,
  showDiff = true,
  theme = 'light'
}) => {
  const [viewMode, setViewMode] = useState<'split' | 'unified'>('split');
  const [selectedOptimizations, setSelectedOptimizations] = useState<string[]>([]);
  const [showDetails, setShowDetails] = useState(false);

  // 计算优化统计
  const optimizationStats = useMemo(() => {
    const stats = {
      total: optimizations.length,
      high: optimizations.filter(o => o.impact === 'HIGH').length,
      medium: optimizations.filter(o => o.impact === 'MEDIUM').length,
      low: optimizations.filter(o => o.impact === 'LOW').length,
      byType: {} as Record<string, number>
    };

    optimizations.forEach(opt => {
      stats.byType[opt.type] = (stats.byType[opt.type] || 0) + 1;
    });

    return stats;
  }, [optimizations]);

  // 应用所有优化
  const handleApplyAll = () => {
    if (onApplyOptimization) {
      onApplyOptimization(optimizedSql);
    }
  };

  // 应用选中的优化
  const handleApplySelected = () => {
    if (onApplyPartialOptimization && selectedOptimizations.length > 0) {
      const selected = optimizations.filter(opt => selectedOptimizations.includes(opt.id));
      onApplyPartialOptimization(selected);
    }
  };

  // 复制到剪贴板
  const handleCopy = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      message.success('已复制到剪贴板');
    });
  };

  // 获取优化类型的显示名称和图标
  const getOptimizationType = (type: string) => {
    const types = {
      'FUNCTION_REPLACE': { name: '函数替换', icon: <SettingOutlined />, color: 'blue' },
      'SYNTAX_ADJUST': { name: '语法调整', icon: <CodeOutlined />, color: 'green' },
      'PERFORMANCE_TUNE': { name: '性能优化', icon: <ThunderboltOutlined />, color: 'orange' },
      'TYPE_CONVERT': { name: '类型转换', icon: <SwapOutlined />, color: 'purple' }
    };
    return types[type as keyof typeof types] || { name: type, icon: <SettingOutlined />, color: 'default' };
  };

  // 获取影响程度的颜色
  const getImpactColor = (impact: string) => {
    switch (impact) {
      case 'HIGH': return '#ff4d4f';
      case 'MEDIUM': return '#faad14';
      case 'LOW': return '#52c41a';
      default: return '#666';
    }
  };

  // 渲染SQL对比视图
  const renderSqlComparison = () => {
    if (viewMode === 'unified') {
      // 统一视图 - 显示差异高亮
      return (
        <Card title="SQL优化对比" className="sql-comparison-card">
          <div className="unified-diff-view">
            {/* 这里可以集成更复杂的diff组件 */}
            <Row gutter={16}>
              <Col span={12}>
                <div className="sql-before">
                  <Title level={5}>优化前</Title>
                  <SyntaxHighlighter
                    language="sql"
                    style={theme === 'dark' ? oneDark : oneLight}
                    customStyle={{ fontSize: 13, borderRadius: 6 }}
                  >
                    {originalSql}
                  </SyntaxHighlighter>
                </div>
              </Col>
              <Col span={12}>
                <div className="sql-after">
                  <Title level={5}>优化后</Title>
                  <SyntaxHighlighter
                    language="sql"
                    style={theme === 'dark' ? oneDark : oneLight}
                    customStyle={{ fontSize: 13, borderRadius: 6 }}
                  >
                    {optimizedSql}
                  </SyntaxHighlighter>
                </div>
              </Col>
            </Row>
          </div>
        </Card>
      );
    }

    return (
      <Row gutter={16}>
        <Col span={12}>
          <Card 
            title="原始SQL" 
            size="small"
            extra={
              <Tooltip title="复制原始SQL">
                <Button 
                  type="text" 
                  icon={<CopyOutlined />} 
                  onClick={() => handleCopy(originalSql)}
                  size="small"
                />
              </Tooltip>
            }
          >
            <SyntaxHighlighter
              language="sql"
              style={theme === 'dark' ? oneDark : oneLight}
              customStyle={{ fontSize: 13, borderRadius: 6, margin: 0 }}
            >
              {originalSql}
            </SyntaxHighlighter>
          </Card>
        </Col>
        <Col span={12}>
          <Card 
            title="优化后SQL" 
            size="small"
            extra={
              <Space>
                <Tooltip title="复制优化后SQL">
                  <Button 
                    type="text" 
                    icon={<CopyOutlined />} 
                    onClick={() => handleCopy(optimizedSql)}
                    size="small"
                  />
                </Tooltip>
                {onApplyOptimization && (
                  <Tooltip title="应用优化">
                    <Button 
                      type="primary" 
                      icon={<CheckOutlined />} 
                      onClick={handleApplyAll}
                      size="small"
                    >
                      应用
                    </Button>
                  </Tooltip>
                )}
              </Space>
            }
          >
            <SyntaxHighlighter
              language="sql"
              style={theme === 'dark' ? oneDark : oneLight}
              customStyle={{ fontSize: 13, borderRadius: 6, margin: 0 }}
            >
              {optimizedSql}
            </SyntaxHighlighter>
          </Card>
        </Col>
      </Row>
    );
  };

  // 渲染优化详情表格
  const renderOptimizationTable = () => {
    if (optimizations.length === 0) return null;

    const columns = [
      {
        title: '选择',
        dataIndex: 'id',
        width: 60,
        render: (id: string) => (
          <Switch
            size="small"
            checked={selectedOptimizations.includes(id)}
            onChange={(checked) => {
              if (checked) {
                setSelectedOptimizations([...selectedOptimizations, id]);
              } else {
                setSelectedOptimizations(selectedOptimizations.filter(sid => sid !== id));
              }
            }}
          />
        )
      },
      {
        title: '优化类型',
        dataIndex: 'type',
        width: 120,
        render: (type: string) => {
          const typeInfo = getOptimizationType(type);
          return (
            <Tag icon={typeInfo.icon} color={typeInfo.color}>
              {typeInfo.name}
            </Tag>
          );
        }
      },
      {
        title: '原始代码',
        dataIndex: 'originalCode',
        width: 150,
        render: (code: string) => (
          <Text code style={{ fontSize: 12, wordBreak: 'break-all' }}>
            {code}
          </Text>
        )
      },
      {
        title: '优化代码',
        dataIndex: 'optimizedCode',
        width: 150,
        render: (code: string) => (
          <Text code style={{ fontSize: 12, color: '#52c41a', wordBreak: 'break-all' }}>
            {code}
          </Text>
        )
      },
      {
        title: '说明',
        dataIndex: 'description',
        ellipsis: true,
        render: (desc: string) => (
          <Tooltip title={desc}>
            <Text style={{ fontSize: 12 }}>{desc}</Text>
          </Tooltip>
        )
      },
      {
        title: '位置',
        dataIndex: 'lineNumber',
        width: 80,
        render: (line: number, record: OptimizationSuggestion) => (
          <Tag>
            {line}:{record.columnNumber}
          </Tag>
        )
      },
      {
        title: '影响程度',
        dataIndex: 'impact',
        width: 100,
        render: (impact: string) => (
          <Tag color={getImpactColor(impact)}>
            {impact}
          </Tag>
        )
      },
      {
        title: '置信度',
        dataIndex: 'confidence',
        width: 80,
        render: (confidence?: number) => (
          confidence ? (
            <Badge 
              count={`${Math.round(confidence * 100)}%`} 
              color={confidence > 0.8 ? 'green' : confidence > 0.6 ? 'orange' : 'red'}
            />
          ) : '-'
        )
      }
    ];

    return (
      <Card 
        title={
          <Space>
            <BulbOutlined />
            优化建议详情
            <Badge count={optimizations.length} color="blue" />
          </Space>
        }
        extra={
          <Space>
            <Text type="secondary" style={{ fontSize: 12 }}>
              已选择 {selectedOptimizations.length} 项
            </Text>
            {selectedOptimizations.length > 0 && onApplyPartialOptimization && (
              <Button 
                type="primary" 
                size="small"
                onClick={handleApplySelected}
              >
                应用选中项
              </Button>
            )}
          </Space>
        }
        style={{ marginTop: 16 }}
      >
        <Table
          dataSource={optimizations}
          columns={columns}
          rowKey="id"
          size="small"
          pagination={false}
          scroll={{ x: 800 }}
        />
      </Card>
    );
  };

  // 渲染优化统计
  const renderOptimizationStats = () => {
    if (optimizations.length === 0) return null;

    return (
      <Card size="small" style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col>
            <Space>
              <Text strong>优化统计:</Text>
              <Badge count={optimizationStats.total} color="blue" title="总优化项" />
              {optimizationStats.high > 0 && (
                <Badge count={optimizationStats.high} color="red" title="高影响项" />
              )}
              {optimizationStats.medium > 0 && (
                <Badge count={optimizationStats.medium} color="orange" title="中影响项" />
              )}
              {optimizationStats.low > 0 && (
                <Badge count={optimizationStats.low} color="green" title="低影响项" />
              )}
            </Space>
          </Col>
          <Col>
            <Space>
              {Object.entries(optimizationStats.byType).map(([type, count]) => {
                const typeInfo = getOptimizationType(type);
                return (
                  <Tag key={type} icon={typeInfo.icon} color={typeInfo.color}>
                    {typeInfo.name}: {count}
                  </Tag>
                );
              })}
            </Space>
          </Col>
        </Row>
      </Card>
    );
  };

  return (
    <div className="optimization-view">
      {/* 工具栏 */}
      <Card size="small" style={{ marginBottom: 16 }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Space>
              <Text strong>视图模式:</Text>
              <Button.Group size="small">
                <Button 
                  type={viewMode === 'split' ? 'primary' : 'default'}
                  onClick={() => setViewMode('split')}
                >
                  <DiffOutlined /> 分栏对比
                </Button>
                <Button 
                  type={viewMode === 'unified' ? 'primary' : 'default'}
                  onClick={() => setViewMode('unified')}
                >
                  <EyeOutlined /> 统一视图
                </Button>
              </Button.Group>
            </Space>
          </Col>
          <Col>
            <Space>
              <Switch
                checked={showDetails}
                onChange={setShowDetails}
                checkedChildren="详情"
                unCheckedChildren="详情"
                size="small"
              />
              <Button icon={<DownloadOutlined />} size="small">
                导出
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 优化统计 */}
      {renderOptimizationStats()}

      {/* SQL对比 */}
      {renderSqlComparison()}

      {/* 优化说明 */}
      {explanation && (
        <Card title="优化说明" style={{ marginTop: 16 }}>
          <Paragraph style={{ fontSize: 14, lineHeight: 1.6 }}>
            {explanation}
          </Paragraph>
        </Card>
      )}

      {/* 优化详情表格 */}
      {showDetails && renderOptimizationTable()}
    </div>
  );
};

export default OptimizationView;